/*
   Copyright (c) 2023 李伟国
   shiro-learner is licensed under Mulan PSL v2.
   You can use this software according to the terms and conditions of the Mulan PSL v2. 
   You may obtain a copy of Mulan PSL v2 at:
            http://license.coscl.org.cn/MulanPSL2 
   THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.  
   See the Mulan PSL v2 for more details. 
*/

package cn.learner.controller;

import cn.learner.config.response.ErrorResponseData;
import cn.learner.config.response.SuccessResponseData;
import cn.learner.constant.enumeration.AuthExceptionEnum;
import cn.learner.controller.base.BaseController;
import cn.learner.dto.LoginDto;
import cn.learner.entity.User;
import cn.learner.config.response.ResponseData;
import cn.learner.exception.AuthException;
import cn.learner.exception.PermissionException;
import cn.learner.service.ILoginService;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@RestController
public class LoginController extends BaseController {
    private static final Logger log = LoggerFactory.getLogger(LoginController.class);
    @Autowired
    private ILoginService loginService;

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public ResponseData login(@RequestBody LoginDto loginDto, HttpServletRequest request){
        String login = loginService.login(loginDto,request);
        log.info(login);
        return new SuccessResponseData(login);
    }

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public ResponseData register(@RequestBody User user){
        loginService.register(user);
        return SUCCESS_INFO;
    }

    @RequestMapping(value = "/logout")
    public ResponseData logout(HttpServletRequest request){
        loginService.logout(request);
        return SUCCESS_INFO;
    }

    @RequestMapping(value = "/un/login", method = RequestMethod.GET)
    public ResponseData unLogin(HttpServletResponse httpServletResponse){
        throw new UnauthenticatedException();   // 未登录
    }

    @RequestMapping("/un/authorized")
    public ResponseData unAuthorized(HttpServletRequest request, HttpServletResponse response){
        throw new UnauthorizedException();  // 无权限
    }

}
